<?php
App::uses('Charset', 'Lib');
App::uses('File', 'Utility');

class EditorsController extends AceAppController {
	private $defaultlevel = 2;
	
	/**
	 * 忽略的文件类型
	 * @var unknown_type
	 */
	private $skip_extensions = array('zip','php','gif','jpg','png','doc','docx','rar','ico');
	private $skip_folders = array();
	private $allow_folders = array();
	
	public function beforeFilter() {
		parent::beforeFilter();
		$this->layout = 'admin_layout';
	}
	
	public function __construct($request = null, $response = null) {
		parent::__construct($request,$response);
		$this->skip_folders = array(
			ROOT.DS.'files',
			ROOT.DS.'img',
			ROOT.DS.'themeroller',				
			ROOT.DS.'lib'.DS.'Cake',
		);

		$this->allow_folders = array(
				//'资源文件(css/img/js)' => WWW_ROOT,
				'前台模板' => ROOT.DS.'app'.DS.'View'.DS.'Themed',
				'后台模板' => ROOT.DS.'manage'.DS.'View'.DS.'Themed',
				'OA模板' => ROOT.DS.'oa'.DS.'View'.DS.'Themed',
		);
	}
	
	public function admin_index(){
		if($this->RequestHandler->isMobile() || $_GET['is_mobile']==1){
    		define('IS_MOBILE',true);
    		$this->theme = Configure::read('Site.mobile_theme');
    		$this->theme = $this->theme?$this->theme:'3g';
    	}
    	else{
    		$this->theme = Configure::read('Site.theme');
    	}
    	
    	if($_GET['theme']){
    		$this->theme = $_GET['theme'];
    	}
    	$this->theme = $this->theme ? $this->theme : 'default';

		$app = $_GET['app'] ? $_GET['app'] : 'app';
		if(!empty($_GET['file'])){
			$edit_file_path = $app . DS.'View' . DS .'Themed'.DS.$this->theme .DS . $_GET['file'];
			if(!file_exists(ROOT . DS .$edit_file_path)) {
				$edit_file_path = $app . DS.'View' . DS.'Themed'.DS.'default' .DS . $_GET['file'];
			}
			if(file_exists(ROOT . DS .$edit_file_path)) {
				$save_file_path = $app . DS.'View' . DS.'Themed'.DS.$this->theme.DS . $_GET['file'];
				$this->set('save_file_path',$save_file_path);
				$this->set('edit_file_path',$edit_file_path);
				$this->set('edit_file_name',$_GET['file']);
			}
		}
		$this->layout = 'admin_layout';
	}
	
	/**
	 * 加载文件内容，将内容转换为utf-8编码。
	 */
	public function admin_loadfile(){
		$file = $_GET['file'];
        $filepath = ROOT. DS.$file;

        $filepath = str_replace(array('/','\\','//','\\\\'),DS,$filepath);

		$content = '';
        if(strpos($filepath,DS.'app'.DS)!==false) {
            $appdir = 'app';
        }
        elseif(strpos($filepath,DS.'manage'.DS)!==false) {
            $appdir = 'manage';
        }
        elseif(strpos($filepath,DS.'oa'.DS)!==false) {
            $appdir = 'oa';
        }

        $name = str_replace(array(
            ROOT.DS,'app','manage',
            DS.'View'.DS.'Themed'.DS,
        ),'',$filepath);

        $data = array(
            'appname' => $appdir,
            'name' => $name,
        );

        $plugPos = strpos($filepath,'Plugin');
        if( $plugPos !== false ) {
            str_replace('Themed'.DS,'',$filepath);
            $filepath = substr($filepath,$plugPos+7);
            list($plugin,$name) = explode(DS.'View'.DS,$filepath);
            $data['plugin'] = $plugin;
            $data['name'] = $name;
        }
        $tplObj = loadModelObject('Template');
        CakeLog::debug( "save db template ".var_export($data,true) );

        $dbtpl = $tplObj->find('first',array(
            'conditions' => $data,
            'limit' => 1,
        ));
        if($dbtpl){
            $content = $dbtpl['Template']['content'];
        }
        elseif(file_exists($filepath)) {
            $content = file_get_contents($filepath);
        }

		$content = Charset::convert_utf8($content);
		echo $content;
		exit;
	}
	
	/**
	 * 
	 * @param string $path 目录
	 * @param int $depth  默认为1，此参数用于递归处理下级目录，限制递归的层级
	 * @param boolean $return	默认为false，此参数用于递归下级目录时，返回结果，否则无返回。
	 */
	public function admin_listfolder($path = ROOT,$depth=1,$return = false){
		$foldertree=array();
		if($depth==1 && $_GET['key']){
			$path = ROOT.$_GET['key'];
		}
		$json = $jsonfiles = array();
		if($path == ROOT || $path==''){
			foreach($this->allow_folders as $key=>$val){
				$json[] = array('isLazy'=>true,'title'=> $key,"isFolder"=> true, "key"=> str_replace(ROOT,'',$val));
					
			}
			$this->set('json',$json);
			$this->set('_serialize','json');
			return ;
		}
		$handle  = opendir($path);
		$i=0;		
		//print_r($this->allow_folders);
		$path = Charset::convert_utf8($path);
		while($file = readdir($handle)){
			$file = Charset::convert_utf8($file);			
			$newpath=$path.DS.$file;
			if(is_dir($newpath)){
				if($file!=".." && $file!="."){
					if(in_array($newpath,$this->skip_folders)){
						continue;
					}
					
					$tmp = array('title'=> $file,"isFolder"=> true, "key"=> str_replace(ROOT,'',$newpath));
					if($depth < $this->defaultlevel){
						$inerprefix = $prefix.$file.'/';
						$tmp['children'] = $this->admin_listfolder($newpath,$depth+1,true);
					}
					else{
						$tmp['isLazy'] = true;	
					}
					$json[] = $tmp; 
				}
			}
			else{
				//echo $path."=======\n";
				
// 				if(!in_array(ROOT.$path,$this->allow_folders)){
// 					continue;
// 				}
				$fileobj = new File($file);
				if(in_array(strtolower($fileobj->ext()),$this->skip_extensions)){
					continue;
				}
				$jsonfiles[] = array('title'=> $file,"key"=> str_replace(ROOT,'',$newpath));
				//$folderfiles[]=$newpath;
				$i++;
			}
		}
		// $json为目录，$jsonfiles 为文件
		$json = array_merge($json,$jsonfiles); // folder文件夹排在前面 
		if($return){
			return $json;
		}
		else{
			$this->set('json',$json);
			$this->set('_serialize','json');
		}
	}
	public function admin_savefile(){
		
		$filename = ROOT.DS.$this->data['name'];
		$filename = str_replace(array('/','\\','//','\\\\'),DS,$filename);
		$allow = false;
		foreach($this->allow_folders as $af){
			if(strpos($filename,$af)!==false){
				$allow = true;
			}
		}
		$info = array('msg'=>'error');
		
		//$file = new File($filename, true);
		if ($allow && !empty($this->data['name']) ) {
			$this->_saveDbTpl( $filename, $this->data['content'] );

			$info = array('msg'=>'save to db success');
			// if ($file->write($this->data['content'])) {
			// 	$info = array('msg'=>'save success');
			// }
			// $file->close();
		}
		echo json_encode($info);
		exit;
	}
	
	private function _saveDbTpl($filepath,$content){

		if(strpos($filepath,DS.'app'.DS)!==false) {
			$appdir = 'app';
		}
		elseif(strpos($filepath,DS.'manage'.DS)!==false) {
			$appdir = 'manage';
		}
		elseif(strpos($filepath,DS.'oa'.DS)!==false) {
			$appdir = 'oa';
		}

		$name = str_replace(array(
			ROOT.DS,'app','manage',
			DS.'View'.DS.'Themed'.DS,
			),'',$filepath);

        $data = array(
            'appname' => $appdir,
            'name' => $name,
        );

        $plugPos = strpos($filepath,'Plugin');
        if( $plugPos !== false ) {
            str_replace('Themed'.DS,'',$filepath);
            $filepath = substr($filepath,$plugPos+7);
            list($plugin,$name) = explode(DS.'View'.DS,$filepath);
            $data['plugin'] = $plugin;
            $data['name'] = $name;
        }
        $tplObj = loadModelObject('Template');
        CakeLog::debug( "save db template ".var_export($data,true) );

        $dbtpl = $tplObj->find('first',array(
            'conditions' => $data,
            'limit' => 1,
        ));
        if($dbtpl) {
        	$dbtpl['Template']['content'] = $content;
        	$tplObj->save($dbtpl);
        }
        else{
        	$data['content'] = $content;
        	$tplObj->save($data);
        }
	}
	
	/**
	 * 修改文件，获取内容
	 * @param unknown_type $filename
	 */
	public function admin_editfile($filepath='index.php'){
        $filepath = ROOT.$filepath;
        $filepath = str_replace(array('/','\\','//','\\\\'),DS,$filepath);

		$allow = false;
		foreach($this->allow_folders as $af){
			if(strpos($filepath,$af)!==false){
				$allow = true;
			}
		}
        $filecontent = '';
		
		if( $allow ){

            if(strpos($filepath,DS.'app'.DS)!==false) {
                $appdir = 'app';
            }
            elseif(strpos($filepath,DS.'manage'.DS)!==false) {
                $appdir = 'manage';
            }
            elseif(strpos($filepath,DS.'oa'.DS)!==false) {
                $appdir = 'oa';
            }

            $name = str_replace(array(
                ROOT.DS,'app','manage',
                DS.'View'.DS.'Themed'.DS,
            ),'',$filepath);

            $data = array(
                'appname' => $appdir,
                'name' => $name,
            );

            $plugPos = strpos($filepath,'Plugin');
            if( $plugPos !== false ) {
                str_replace('Themed'.DS,'',$filepath);
                $filepath = substr($filepath,$plugPos+7);
                list($plugin,$name) = explode(DS.'View'.DS,$filepath);
                $data['plugin'] = $plugin;
                $data['name'] = $name;
            }
            $tplObj = loadModelObject('Template');
            CakeLog::debug( "save db template ".var_export($data,true) );

            $dbtpl = $tplObj->find('first',array(
                'conditions' => $data,
                'limit' => 1,
            ));
            if($dbtpl){

            }
            elseif(file_exists($filepath)) {
                $filecontent = file_get_contents($filepath);
            }

		}
		$this->set('filecontent',$filecontent);
	}
}
?>